package com.g4m.baselib.component;

import com.g4m.baselib.entity.Response;
import com.g4m.baselib.entity.WebConstants;
import com.g4m.baselib.tool.ClientInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created on 2020-01-01
 * <p>Copyright 2008-2020 snsndk.com</p>
 * <p>
 * hudesen[hudesen@hudesen.com]
 */
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandlerController {


    /**
     * 请求结果
     *
     * @param request             请求
     * @param httpServletResponse 返回
     * @param e                   error
     * @return res
     */
    @ExceptionHandler(value = Exception.class)
    public Response exceptionHandler(HttpServletRequest request, HttpServletResponse httpServletResponse, Exception e) {
        log.error("服务器内部错误:{},uri:{}", ExceptionUtils.getStackTrace(e), request.getRequestURI());
        ClientInfo.addCrossDomain(request, httpServletResponse);
        return Response.buildResponse(WebConstants.RESPONSE_RESULT_SYSTEM_ERROR);
    }

    /**
     * 没权限
     *
     * @param request  请求
     * @param response 返回
     * @param e        error
     * @return res
     */
    @ExceptionHandler(value = PremissionException.class)
    public Response permissionExceptionHandler(HttpServletRequest request, HttpServletResponse response, PremissionException e) {
        log.debug("PermissionException:{},uri:{}", ExceptionUtils.getStackTrace(e), request.getRequestURI());
        ClientInfo.addCrossDomain(request, response);
        return Response.buildResponse(WebConstants.RESPONSE_RESULT_NEED_LOGIN);
    }
}
